<template>
  <div>
    <ul class="matchList">
      <li v-for="(val, index) in list" :key="index.id">
        <div class="img"><img :src="val.logo" alt="" /></div>
        <div class="left">
          <p class="name">
            <span>{{ val.name }}</span>
						<span v-if="val.surplus!='已过支付时间'&&val.is_pay==0" style="font-size:0.2rem;text-align:right;width:48%;">剩余支付时间:{{val.surplus}}</span>
						<span v-if="val.surplus=='已过支付时间'&&val.is_pay==0" style="font-size:0.2rem;text-align:right;width:48%;">{{val.surplus}}</span>
          </p>
          <p class="host">项目组别：{{ val.group }}<span v-if="val.group">-</span>{{ val.type }}</p>
          <p class="host">主办方：{{ val.host }}</p>
          <p class="date">比赛开始时间：{{ val.start_time }}</p>
          <div class="btns">
            <div class="border-green-btn btn" @click="cancelOrder(val.project_id, val.sign_id, val.user_id, index)"
              v-if="val.is_pay == 0">取消订单</div>
            <div class="border-green-btn btn" @click="weixinPay(val.project_id, val.sign_id, val.user_id)" v-if="val.is_pay == 0">立即缴费</div>
            <div class="border-green-btn btn" @click="weixinRefund(val.project_id, val.user_id, index, 0)" v-if="(val.status == 2 || val.status == 3) && val.is_pay == 1 && val.refund_status == 1">
              申请退赛
            </div>
            <div class="border-green-btn btn" v-if="(val.status == 2 || val.status == 3) && val.is_pay == 1 && val.refund_status == 2"
              @click="weixinRefund(val.project_id, val.user_id, index, 1)">取消退赛</div>
            <span class="green-btn btn" v-if="val.status == 2">未开始</span>
            <span class="green-btn btn" v-if="val.status == 3">未开始</span>
            <span class="green-btn btn" v-if="val.status == 4">进行中</span>
            <span class="green-btn btn" v-if="val.status == 5">已结束</span>
            <div class="border-green-btn btn" @click="check_match(val.project_id, val.name, val.logo, val.group, val.type)" v-if="val.status == 4 || val.status == 5">参赛情况</div>
            <div class="border-green-btn btn" @click="checkDetails(val.com_id, val.name, val.status)" v-if="val.status == 4 || val.status == 5">查看详情</div>
          </div>
        </div>
      </li>
    </ul>
    <div class="notInfo" v-if="list.length == 0">暂无信息</div>
  </div>
</template>
<script>
  import eventBus from '../../../../build/evenBugTab.js';
  import {
    Dialog
  } from 'vant';
  import {
    Toast
  } from 'vant';
  export default {
    data() {
      return {
        matchList: [],
        list: [], // 存储数据的数组
        flag: true,
        sum: false,
        items: [],
        offset: 0,
        limit: 10,
        status: '2,3,4,5',
        noDate: false,
				countTime:1800,
				interval:''
      };
    },
    mounted() {
      this.getDate();
      eventBus.$on('tabs_on', newValue => {
        this.status = newValue;
        this.getDate();
      });
			let _this = this; // 声明一个变量指向Vue实例this，保证作用域一致
			// this.timer = setInterval(() => {
			// 	_this.date =this.getTime(); // 修改数据date
			// }, 1000)
    },
		created() {
			// this.countTime()
		},
    beforeDestroy() {
      //解决eventbus 多次触发的问题
      eventBus.$off('tabs_on');
			// 在Vue实例销毁前，清除我们的定时器
			if (this.timer) {
				clearInterval(this.timer); 
			}
    },
    methods: {
			// 计算剩余支付时间
			// countTime(){
				
			// },
			// 获取当前时间
			getTime(index){
				const that = this
				that.interval = setInterval(() => {
					if(that.countTime == 0) {
							// 计时结束，清除缓存
							clearInterval(that.interval)
						} else {
							that.countTime--
							let day = parseInt(that.countTime / 60 / 60 / 24)
							let hr = parseInt(that.countTime / 60 / 60 % 24)
							let min = parseInt(that.countTime / 60 % 60)
							let sec = parseInt(that.countTime % 60)
				
							day = day > 9 ? day : '0' + day
							hr = hr > 9 ? hr : '0' + hr
							min = min > 9 ? min : '0' + min
							sec = sec > 9 ? sec : '0' + sec
							// that.list[index].surplus = `${min}分${sec}秒`
							var surplus = `${min}分${sec}秒`
							this.list[index].surplus = surplus
						}
				}, 1000)
			},
      check_match(project_id, name, logo, group, type){
        this.$router.push({
          path: '/match/checkApply',
          query: {
            group_id: project_id,
            name: name,
            logo: logo,
            perject_name: `${group}${type}`
          }
        });
      },
      //申请退款
      weixinRefund(group_id, user_id, index, type) {
        Dialog.confirm({
            title: '提示',
            message: '确定申请退赛？'
          })
          .then(() => {
            let params = new URLSearchParams();
            params.append('group_id', group_id);
            params.append('user_id', user_id);
            params.append('type', type);
            this.$axios
              .post('/mobile/v1/PersonalCenter/apply_refund', params, {
                headers: {
                  token: window.sessionStorage.getItem('token')
                }
              })
              .then(res => {
                if (res.data.code == 2000) {
                  if (type == 0) {
                    this.list[index].refund_status = 2;
                  } else if (type == 1) {
                    this.list[index].refund_status = 1;
                  }
                  Toast(res.data.msg);
                } else {
                  Toast(res.data.msg);
                }
              })
              .catch(res => {
                //  console.log(res.msg);
              });
          })
          .catch(() => {});
      },
      checkDetails(com_id, name, status) {
        localStorage.setItem('index', com_id);
        localStorage.setItem('name', name);
        if (status == 2 || status == 3) {
          this.$router.push({
            path: '/match/detail/MatchDetailNoGoing',
            query: {
              id: com_id,
              name: name,
              defaultId: 2
            }
          });
        }
        if (status == 4) {
          this.$router.push({
            path: '/match/detail/MatchDetailGoing',
            query: {
              id: com_id,
              name: name,
              defaultId: 2
            }
          });
        }
        if (status == 5) {
          this.$router.push({
            path: '/match/detail/MatchDetailEnd',
            query: {
              id: com_id,
              name: name,
              defaultId: 2
            }
          });
        }
      },
      cancelOrder(project_id, sign_id, user_id, index) {
        Dialog.confirm({
            title: '标题',
            message: '取消订单？'
          })
          .then(() => {
            var params = new URLSearchParams();
            params.append('project_id', project_id);
            params.append('sign_id', sign_id);
            this.$axios
              .post('/mobile/v1/PersonalCenter/cancel_order', params, {
                headers: {
                  token: window.sessionStorage.getItem('token')
                }
              })
              .then(res => {
                if (res.data.code == 2000) {
                  this.list.splice(index, 1);
                  Toast(res.data.msg);
                } else {
                  Toast(res.data.msg);
                }
              })
              .catch(res => {
                //  console.log(res.msg);
              });
          })
          .catch(() => {});
      },
      weixinPay(project_id, sign_id, user_id) {
        if (sign_id == user_id) {
          this.$axios
            .get('/mobile/v1/Orderpay/wx_pay', {
              params: {
                project_id: project_id
              },
              headers: {
                token: window.sessionStorage.getItem('token')
              }
            })
            .then(res => {
              if (res.data.code == 2000) {
                this.weixinPays(res.data.data);
              } else {
                Toast(res.data.msg);
              }
            })
            .catch(res => {
              //  console.log(res.msg);
            });
        } else {
          Toast('sign_id不等于user_id');
        }
      },
      weixinPays(data) {
        var vm = this;
        if (typeof WeixinJSBridge == 'undefined') {
          //微信浏览器内置对象。参考微信官方文档
          Toast('不是微信环境,无法调起支付');
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(data), false);
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data));
            document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady(data));
          }
        } else {
          vm.onBridgeReady(data);
        }
      },
      onBridgeReady(data) {
        var vm = this;
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', {
            appId: data.appId, //公众号名称，由商户传入
            timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
            nonceStr: data.nonceStr, //随机串
            package: data.package,
            signType: data.signType, //微信签名方式：
            paySign: data.paySign //微信签名
          },
          function(res) {
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            if (res.err_msg == 'get_brand_wcpay_request:ok') {
              vm.$toast('支付成功');
              // vm.is_pay = 1;
              setTimeout(() => {
                vm.$router.push({
                  path: '/mine'
                });
              }, 100);
            } else {
              vm.$toast('支付失败');
            }
          }
        );
      },
      getDate(fn) {
				const that = this
        this.$axios
          .get('/mobile/v1/PersonalCenter/getmycompe', {
            params: {
              status: that.status
            },
            headers: {
              token: window.sessionStorage.getItem('token')
            }
          })
          .then(data => {
            if (data.data.code == 200) {
              that.list = data.data.data;
            } else {
              that.list = data.data.data;
              return false;
            }
						
						for(var index in that.list){
							// 判断时间
							let currentTime = Math.round(new Date() / 1000) //当前时间
							let createdTime = this.list[index].create_time || this.list[index].create_time //下单时间
							let countTime = Math.abs(createdTime - currentTime )
							if(countTime >= 1800){
								that.list[index].surplus = '已过支付时间'
							}else{
								// countTime--
								// let day = parseInt(that.countTime / 60 / 60 / 24)
								// let hr = parseInt(that.countTime / 60 / 60 % 24)
								let min = parseInt(countTime / 60 % 60)
								let sec = parseInt(countTime % 60)
												
								// day = day > 9 ? day : '0' + day
								// hr = hr > 9 ? hr : '0' + hr
								min = min > 9 ? min : '0' + min
								// sec = sec > 9 ? sec : '0' + sec
								var surplus = `${30 - min}分钟`
								that.list[index].surplus = surplus
								// that.list[index].surplus = surplus
								// that.getTime(index)
							}
						}
          })
          .catch(error => {
            // console.log(error);
          });
      }
    }
  };
</script>
<style lang="less" scoped>
	
  .van-cell__right-icon {
    font-size: 12px;
  }

  .matchList {
    padding: 0.1rem 0.3rem;
    width: 100%;
    box-sizing: border-box;

    li {
      margin-bottom: 0.2rem;
      // box-shadow: 1px 1px 1px #eaeaea;
      width: 100%;
      padding: 0.1rem 0rem 0.2rem 0rem;
      box-sizing: border-box;
      position: relative;
      display: flex;
      justify-content: space-between;
      text-align: left;
      color: #413e3a;
      overflow: hidden;
      border-bottom: 1px #ccc dotted;

      .img {
        flex: 0.2;
        margin-right: 0.2rem;
        width: 20%;

        img {
          display: inline-block;
          padding-top: 0.2rem;
          width: 1rem;
          height: 1rem;
        }
      }

      .left {
        flex: 1;
        width: 80%;

        .name {
          font-weight: 600;
          font-size: 0.32rem;
          line-height: 0.6rem;
          width: 100%;
          overflow: hidden;
          white-space: nowrap;
          display: flex;
          justify-content: space-between;

          span {
            display: inline-block;
            width: 70%;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }

          a {
            display: inline-block;
            width: 25%;
            font-size: 0.28rem;
            color: #c8c8c8;
          }
        }

        .host,
        .adress,
        .time {
          line-height: 0.46rem;
        }

        .btns {
          margin-top: 0.1rem;

          .btn {}

          .btn+.btn {
            margin-right: 0.2rem;
          }

          .green-btn {
            width: 21vw;
            height: 0.5rem;
            line-height: 0.5rem;
            float: right;
            background-color: #42b574;
            color: #fff;
            text-align: center;
          }

          .border-green-btn {
            width: 21vw;
            height: 0.48rem;
            line-height: 0.48rem;
            float: right;
            background-color: #fff;
            border: 0.01rem solid #42b574;
            color: #42b574;
            text-align: center;
          }

          /*.border-green-btn:hover{*/
          /*transition: 0.5s;*/
          /*background-color: #42b574;*/
          /*color:#fff;*/
          /*}*/
        }
      }
    }
  }
</style>
